3 * Contain classes to list log entries
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
26 use MediaWiki\Linker\LinkRenderer
;
27 use MediaWiki\MediaWikiServices
;
28 use Wikimedia\Rdbms\IDatabase
;
30 class LogEventsList
extends ContextSource
{
31 const NO_ACTION_LINK
= 1;
32 const NO_EXTRA_USER_LINKS
= 2;
33 const USE_CHECKBOXES
= 4;
40 protected $mDefaultQuery;
45 protected $showTagEditUI;
50 protected $allowedActions = null;
53 * @var LinkRenderer|null
55 private $linkRenderer;
58 * The first two parameters used to be $skin and $out, but now only a context
59 * is needed, that's why there's a second unused parameter.
61 * @param IContextSource|Skin $context Context to use; formerly it was
62 * a Skin object. Use of Skin is deprecated.
63 * @param LinkRenderer|null $linkRenderer previously unused
64 * @param int $flags Can be a combination of self::NO_ACTION_LINK,
65 * self::NO_EXTRA_USER_LINKS or self::USE_CHECKBOXES.
67 public function __construct( $context, $linkRenderer = null, $flags = 0 ) {
68 if ( $context instanceof IContextSource
) {
69 $this->setContext( $context );
71 // Old parameters, $context should be a Skin object
72 $this->setContext( $context->getContext() );
75 $this->flags
= $flags;
76 $this->showTagEditUI
= ChangeTags
::showTagEditingUI( $this->getUser() );
77 if ( $linkRenderer instanceof LinkRenderer
) {
78 $this->linkRenderer
= $linkRenderer;
84 * @return LinkRenderer
86 protected function getLinkRenderer() {
87 if ( $this->linkRenderer
!== null ) {
88 return $this->linkRenderer
;
90 return MediaWikiServices
::getInstance()->getLinkRenderer();
95 * Show options for the log list
97 * @param array|string $types
100 * @param bool $pattern
101 * @param int|string $year Use 0 to start with no year preselected.
102 * @param int|string $month A month in the 1..12 range. Use 0 to start with no month
104 * @param int|string $day A day in the 1..31 range. Use 0 to start with no month
106 * @param array|null $filter
107 * @param string $tagFilter Tag to select by default
108 * @param string|null $action
110 public function showOptions( $types = [], $user = '', $page = '', $pattern = false, $year = 0,
111 $month = 0, $day = 0, $filter = null, $tagFilter = '', $action = null
113 // For B/C, we take strings, but make sure they are converted...
114 $types = ( $types === '' ) ?
[] : (array)$types;
116 $formDescriptor = [];
119 $formDescriptor['type'] = $this->getTypeMenuDesc( $types );
120 $formDescriptor['user'] = $this->getUserInputDesc( $user );
121 $formDescriptor['page'] = $this->getTitleInputDesc( $page );
123 // Add extra inputs if any
124 // This could either be a form descriptor array or a string with raw HTML.
125 // We need it to work in both cases and show a deprecation warning if it
126 // is a string. See T199495.
127 $extraInputsDescriptor = $this->getExtraInputsDesc( $types );
129 is_array( $extraInputsDescriptor ) &&
130 !empty( $extraInputsDescriptor )
132 $formDescriptor[ 'extra' ] = $extraInputsDescriptor;
133 } elseif ( is_string( $extraInputsDescriptor ) ) {
134 // We'll add this to the footer of the form later
135 $extraInputsString = $extraInputsDescriptor;
136 wfDeprecated( 'Using $input in LogEventsListGetExtraInputs hook', '1.32' );
139 // Title pattern, if allowed
140 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
141 $formDescriptor['pattern'] = $this->getTitlePatternDesc( $pattern );
145 $formDescriptor['date'] = [
147 'label-message' => 'date'
151 $formDescriptor['tagfilter'] = [
152 'type' => 'tagfilter',
153 'name' => 'tagfilter',
154 'label-raw' => $this->msg( 'tag-filter' )->parse(),
159 $formDescriptor['filters'] = $this->getFiltersDesc( $filter );
165 $this->allowedActions
!== null &&
166 count( $this->allowedActions
) > 0
168 $formDescriptor['subtype'] = $this->getActionSelectorDesc( $types, $action );
171 $context = new DerivativeContext( $this->getContext() );
172 $context->setTitle( SpecialPage
::getTitleFor( 'Log' ) ); // Remove subpage
173 $htmlForm = new HTMLForm( $formDescriptor, $context );
175 ->setSubmitText( $this->msg( 'logeventslist-submit' )->text() )
177 ->setWrapperLegendMsg( 'log' );
179 // TODO This will should be removed at some point. See T199495.
180 if ( isset( $extraInputsString ) ) {
181 $htmlForm->addFooterText( Html
::rawElement(
188 $htmlForm->prepareForm()->displayForm( false );
192 * @param array $filter
193 * @return array Form descriptor
195 private function getFiltersDesc( $filter ) {
198 foreach ( $filter as $type => $val ) {
199 $message = $this->msg( "logeventslist-{$type}-log" );
200 // FIXME: Remove this check once T199657 is fully resolved.
201 if ( !$message->exists() ) {
202 $message = $this->msg( "log-show-hide-{$type}" )->params( $this->msg( 'show' )->text() );
204 $options[ $message->text() ] = $type;
206 if ( $val === false ) {
211 'class' => 'HTMLMultiSelectField',
212 'label-message' => 'logeventslist-more-filters',
214 'options' => $options,
215 'default' => $default,
219 private function getDefaultQuery() {
220 if ( !isset( $this->mDefaultQuery
) ) {
221 $this->mDefaultQuery
= $this->getRequest()->getQueryValues();
222 unset( $this->mDefaultQuery
['title'] );
223 unset( $this->mDefaultQuery
['dir'] );
224 unset( $this->mDefaultQuery
['offset'] );
225 unset( $this->mDefaultQuery
['limit'] );
226 unset( $this->mDefaultQuery
['order'] );
227 unset( $this->mDefaultQuery
['month'] );
228 unset( $this->mDefaultQuery
['year'] );
231 return $this->mDefaultQuery
;
235 * @param array $queryTypes
236 * @return array Form descriptor
238 private function getTypeMenuDesc( $queryTypes ) {
239 $queryType = count( $queryTypes ) == 1 ?
$queryTypes[0] : '';
241 $typesByName = []; // Temporary array
242 // First pass to load the log names
243 foreach ( LogPage
::validTypes() as $type ) {
244 $page = new LogPage( $type );
245 $restriction = $page->getRestriction();
246 if ( $this->getUser()->isAllowed( $restriction ) ) {
247 $typesByName[$type] = $page->getName()->text();
251 // Second pass to sort by name
252 asort( $typesByName );
254 // Always put "All public logs" on top
255 $public = $typesByName[''];
256 unset( $typesByName[''] );
257 $typesByName = [ '' => $public ] +
$typesByName;
260 'class' => 'HTMLSelectField',
262 'options' => array_flip( $typesByName ),
263 'default' => $queryType,
268 * @param string $user
269 * @return array Form descriptor
271 private function getUserInputDesc( $user ) {
273 'class' => 'HTMLUserTextField',
274 'label-message' => 'specialloguserlabel',
280 * @param string $title
281 * @return array Form descriptor
283 private function getTitleInputDesc( $title ) {
285 'class' => 'HTMLTitleTextField',
286 'label-message' => 'speciallogtitlelabel',
293 * @param bool $pattern
294 * @return array Form descriptor
296 private function getTitlePatternDesc( $pattern ) {
299 'label-message' => 'log-title-wildcard',
305 * @param array $types
306 * @return array|string Form descriptor or string with HTML
308 private function getExtraInputsDesc( $types ) {
309 if ( count( $types ) == 1 ) {
310 if ( $types[0] == 'suppress' ) {
313 'label-message' => 'revdelete-offender',
314 'name' => 'offender',
317 // Allow extensions to add their own extra inputs
318 // This could be an array or string. See T199495.
319 $input = ''; // Deprecated
320 $formDescriptor = [];
321 Hooks
::run( 'LogEventsListGetExtraInputs', [ $types[0], $this, &$input, &$formDescriptor ] );
323 return empty( $formDescriptor ) ?
$input : $formDescriptor;
331 * Drop down menu for selection of actions that can be used to filter the log
332 * @param array $types
333 * @param string $action
334 * @return array Form descriptor
336 private function getActionSelectorDesc( $types, $action ) {
338 $actionOptions[ 'log-action-filter-all' ] = '';
340 foreach ( $this->allowedActions
as $value ) {
341 $msgKey = 'log-action-filter-' . $types[0] . '-' . $value;
342 $actionOptions[ $msgKey ] = $value;
346 'class' => 'HTMLSelectField',
348 'options-messages' => $actionOptions,
349 'default' => $action,
350 'label' => $this->msg( 'log-action-filter-' . $types[0] )->text(),
355 * Sets the action types allowed for log filtering
356 * To one action type may correspond several log_actions
357 * @param array $actions
360 public function setAllowedActions( $actions ) {
361 $this->allowedActions
= $actions;
367 public function beginLogEventsList() {
374 public function endLogEventsList() {
379 * @param stdClass $row A single row from the result set
380 * @return string Formatted HTML list item
382 public function logLine( $row ) {
383 $entry = DatabaseLogEntry
::newFromRow( $row );
384 $formatter = LogFormatter
::newFromEntry( $entry );
385 $formatter->setContext( $this->getContext() );
386 $formatter->setLinkRenderer( $this->getLinkRenderer() );
387 $formatter->setShowUserToolLinks( !( $this->flags
& self
::NO_EXTRA_USER_LINKS
) );
389 $time = htmlspecialchars( $this->getLanguage()->userTimeAndDate(
390 $entry->getTimestamp(), $this->getUser() ) );
392 $action = $formatter->getActionText();
394 if ( $this->flags
& self
::NO_ACTION_LINK
) {
397 $revert = $formatter->getActionLinks();
398 if ( $revert != '' ) {
399 $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>';
403 $comment = $formatter->getComment();
405 // Some user can hide log items and have review links
406 $del = $this->getShowHideLinks( $row );
409 list( $tagDisplay, $newClasses ) = ChangeTags
::formatSummaryRow(
414 $classes = array_merge(
415 [ 'mw-logline-' . $entry->getType() ],
419 'data-mw-logid' => $entry->getId(),
420 'data-mw-logaction' => $entry->getFullType(),
422 $ret = "$del $time $action $comment $revert $tagDisplay";
424 // Let extensions add data
425 Hooks
::run( 'LogEventsListLineEnding', [ $this, &$ret, $entry, &$classes, &$attribs ] );
426 $attribs = array_filter( $attribs,
427 [ Sanitizer
::class, 'isReservedDataAttribute' ],
430 $attribs['class'] = implode( ' ', $classes );
432 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
436 * @param stdClass $row
439 private function getShowHideLinks( $row ) {
440 // We don't want to see the links and
441 if ( $this->flags
== self
::NO_ACTION_LINK
) {
445 $user = $this->getUser();
447 // If change tag editing is available to this user, return the checkbox
448 if ( $this->flags
& self
::USE_CHECKBOXES
&& $this->showTagEditUI
) {
452 [ 'name' => 'ids[' . $row->log_id
. ']' ]
456 // no one can hide items from the suppress log.
457 if ( $row->log_type
== 'suppress' ) {
462 // Don't show useless checkbox to people who cannot hide log entries
463 if ( $user->isAllowed( 'deletedhistory' ) ) {
464 $canHide = $user->isAllowed( 'deletelogentry' );
465 $canViewSuppressedOnly = $user->isAllowed( 'viewsuppressed' ) &&
466 !$user->isAllowed( 'suppressrevision' );
467 $entryIsSuppressed = self
::isDeleted( $row, LogPage
::DELETED_RESTRICTED
);
468 $canViewThisSuppressedEntry = $canViewSuppressedOnly && $entryIsSuppressed;
469 if ( $row->log_deleted ||
$canHide ) {
470 // Show checkboxes instead of links.
471 if ( $canHide && $this->flags
& self
::USE_CHECKBOXES
&& !$canViewThisSuppressedEntry ) {
472 // If event was hidden from sysops
473 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
474 $del = Xml
::check( 'deleterevisions', false, [ 'disabled' => 'disabled' ] );
479 [ 'name' => 'ids[' . $row->log_id
. ']' ]
483 // If event was hidden from sysops
484 if ( !self
::userCan( $row, LogPage
::DELETED_RESTRICTED
, $user ) ) {
485 $del = Linker
::revDeleteLinkDisabled( $canHide );
488 'target' => SpecialPage
::getTitleFor( 'Log', $row->log_type
)->getPrefixedDBkey(),
490 'ids' => $row->log_id
,
492 $del = Linker
::revDeleteLink(
495 $canHide && !$canViewThisSuppressedEntry
506 * @param stdClass $row
507 * @param string|array $type
508 * @param string|array $action
509 * @param string $right
512 public static function typeAction( $row, $type, $action, $right = '' ) {
513 $match = is_array( $type ) ?
514 in_array( $row->log_type
, $type ) : $row->log_type
== $type;
516 $match = is_array( $action ) ?
517 in_array( $row->log_action
, $action ) : $row->log_action
== $action;
518 if ( $match && $right ) {
520 $match = $wgUser->isAllowed( $right );
528 * Determine if the current user is allowed to view a particular
529 * field of this log row, if it's marked as deleted.
531 * @param stdClass $row
533 * @param User|null $user User to check, or null to use $wgUser
536 public static function userCan( $row, $field, User
$user = null ) {
537 return self
::userCanBitfield( $row->log_deleted
, $field, $user );
541 * Determine if the current user is allowed to view a particular
542 * field of this log row, if it's marked as deleted.
544 * @param int $bitfield Current field
546 * @param User|null $user User to check, or null to use $wgUser
549 public static function userCanBitfield( $bitfield, $field, User
$user = null ) {
550 if ( $bitfield & $field ) {
551 if ( $user === null ) {
555 if ( $bitfield & LogPage
::DELETED_RESTRICTED
) {
556 $permissions = [ 'suppressrevision', 'viewsuppressed' ];
558 $permissions = [ 'deletedhistory' ];
560 $permissionlist = implode( ', ', $permissions );
561 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
562 return $user->isAllowedAny( ...$permissions );
568 * @param stdClass $row
569 * @param int $field One of DELETED_* bitfield constants
572 public static function isDeleted( $row, $field ) {
573 return ( $row->log_deleted
& $field ) == $field;
577 * Show log extract. Either with text and a box (set $msgKey) or without (don't set $msgKey)
579 * @param OutputPage|string &$out
580 * @param string|array $types Log types to show
581 * @param string|Title $page The page title to show log entries for
582 * @param string $user The user who made the log entries
583 * @param array $param Associative Array with the following additional options:
584 * - lim Integer Limit of items to show, default is 50
585 * - conds Array Extra conditions for the query
586 * (e.g. 'log_action != ' . $dbr->addQuotes( 'revision' ))
587 * - showIfEmpty boolean Set to false if you don't want any output in case the loglist is empty
588 * if set to true (default), "No matching items in log" is displayed if loglist is empty
589 * - msgKey Array If you want a nice box with a message, set this to the key of the message.
590 * First element is the message key, additional optional elements are parameters for the key
591 * that are processed with wfMessage
592 * - offset Set to overwrite offset parameter in WebRequest
593 * set to '' to unset offset
594 * - wrap String Wrap the message in html (usually something like "<div ...>$1</div>").
595 * - flags Integer display flags (NO_ACTION_LINK,NO_EXTRA_USER_LINKS)
596 * - useRequestParams boolean Set true to use Pager-related parameters in the WebRequest
597 * - useMaster boolean Use master DB
598 * - extraUrlParams array|bool Additional url parameters for "full log" link (if it is shown)
599 * @return int Number of total log items (not limited by $lim)
601 public static function showLogExtract(
602 &$out, $types = [], $page = '', $user = '', $param = []
604 $defaultParameters = [
607 'showIfEmpty' => true,
611 'useRequestParams' => false,
612 'useMaster' => false,
613 'extraUrlParams' => false,
615 # The + operator appends elements of remaining keys from the right
616 # handed array to the left handed, whereas duplicated keys are NOT overwritten.
617 $param +
= $defaultParameters;
618 # Convert $param array to individual variables
619 $lim = $param['lim'];
620 $conds = $param['conds'];
621 $showIfEmpty = $param['showIfEmpty'];
622 $msgKey = $param['msgKey'];
623 $wrap = $param['wrap'];
624 $flags = $param['flags'];
625 $extraUrlParams = $param['extraUrlParams'];
627 $useRequestParams = $param['useRequestParams'];
628 if ( !is_array( $msgKey ) ) {
629 $msgKey = [ $msgKey ];
632 if ( $out instanceof OutputPage
) {
633 $context = $out->getContext();
635 $context = RequestContext
::getMain();
638 // FIXME: Figure out how to inject this
639 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
641 # Insert list of top 50 (or top $lim) items
642 $loglist = new LogEventsList( $context, $linkRenderer, $flags );
643 $pager = new LogPager( $loglist, $types, $user, $page, '', $conds );
644 if ( !$useRequestParams ) {
645 # Reset vars that may have been taken from the request
647 $pager->mDefaultLimit
= 50;
648 $pager->mOffset
= "";
649 $pager->mIsBackwards
= false;
652 if ( $param['useMaster'] ) {
653 $pager->mDb
= wfGetDB( DB_MASTER
);
655 if ( isset( $param['offset'] ) ) { # Tell pager to ignore WebRequest offset
656 $pager->setOffset( $param['offset'] );
660 $pager->mLimit
= $lim;
662 // Fetch the log rows and build the HTML if needed
663 $logBody = $pager->getBody();
664 $numRows = $pager->getNumRows();
670 $dir = $context->getLanguage()->getDir();
671 $lang = $context->getLanguage()->getHtmlCode();
673 $s = Xml
::openElement( 'div', [
674 'class' => "mw-warning-with-logexcerpt mw-content-$dir",
679 if ( count( $msgKey ) == 1 ) {
680 $s .= $context->msg( $msgKey[0] )->parseAsBlock();
681 } else { // Process additional arguments
683 array_shift( $args );
684 $s .= $context->msg( $msgKey[0], $args )->parseAsBlock();
687 $s .= $loglist->beginLogEventsList() .
689 $loglist->endLogEventsList();
690 } elseif ( $showIfEmpty ) {
691 $s = Html
::rawElement( 'div', [ 'class' => 'mw-warning-logempty' ],
692 $context->msg( 'logempty' )->parse() );
695 if ( $numRows > $pager->mLimit
) { # Show "Full log" link
697 if ( $page instanceof Title
) {
698 $urlParam['page'] = $page->getPrefixedDBkey();
699 } elseif ( $page != '' ) {
700 $urlParam['page'] = $page;
704 $urlParam['user'] = $user;
707 if ( !is_array( $types ) ) { # Make it an array, if it isn't
711 # If there is exactly one log type, we can link to Special:Log?type=foo
712 if ( count( $types ) == 1 ) {
713 $urlParam['type'] = $types[0];
716 if ( $extraUrlParams !== false ) {
717 $urlParam = array_merge( $urlParam, $extraUrlParams );
720 $s .= $linkRenderer->makeKnownLink(
721 SpecialPage
::getTitleFor( 'Log' ),
722 $context->msg( 'log-fulllog' )->text(),
728 if ( $logBody && $msgKey[0] ) {
732 if ( $wrap != '' ) { // Wrap message in html
733 $s = str_replace( '$1', $s, $wrap );
736 /* hook can return false, if we don't want the message to be emitted (Wikia BugId:7093) */
737 if ( Hooks
::run( 'LogEventsListShowLogExtract', [ &$s, $types, $page, $user, $param ] ) ) {
738 // $out can be either an OutputPage object or a String-by-reference
739 if ( $out instanceof OutputPage
) {
750 * SQL clause to skip forbidden log types for this user
752 * @param IDatabase $db
753 * @param string $audience Public/user
754 * @param User|null $user User to check, or null to use $wgUser
755 * @return string|bool String on success, false on failure.
757 public static function getExcludeClause( $db, $audience = 'public', User
$user = null ) {
758 global $wgLogRestrictions;
760 if ( $audience != 'public' && $user === null ) {
765 // Reset the array, clears extra "where" clauses when $par is used
768 // Don't show private logs to unprivileged users
769 foreach ( $wgLogRestrictions as $logType => $right ) {
770 if ( $audience == 'public' ||
!$user->isAllowed( $right ) ) {
771 $hiddenLogs[] = $logType;
774 if ( count( $hiddenLogs ) == 1 ) {
775 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
776 } elseif ( $hiddenLogs ) {
777 return 'log_type NOT IN (' . $db->makeList( $hiddenLogs ) . ')';